#include "StdAfx.h"
#include "PhysicsWorld.h"
#include "PhysicalObject.h"

#include <Havok\Source\Common/Base/Memory/System/Util/hkMemoryInitUtil.h>
#include <Havok\Source\Common/Base/Memory/Allocator/Malloc/hkMallocAllocator.h>

static void HK_CALL errorReport(const char* msg, void* userContext)
{
	using namespace std;
	OutputDebugString((LPCWSTR)msg);
}

PhysicsWorld::PhysicsWorld(float fSize)
{
	hkMallocAllocator baseMalloc;
	// Need to have memory allocated for the solver. Allocate 1mb for it.
	hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault( &baseMalloc, hkMemorySystem::FrameInfo(1024 * 1024) );
	hkBaseSystem::init( memoryRouter, errorReport );	

	hkpWorldCinfo info;
	info.m_gravity.set( 0,-9.8f,0);
	info.setBroadPhaseWorldSize( fSize );
	info.setupSolverInfo( hkpWorldCinfo::SOLVER_TYPE_4ITERS_MEDIUM );	
	m_World = new hkpWorld( info );

	hkpAgentRegisterUtil::registerAllAgents( m_World->getCollisionDispatcher() );
}


PhysicsWorld::~PhysicsWorld(void)
{
	m_World->removeReference();

	hkBaseSystem::quit();
	hkMemoryInitUtil::quit();
}

void PhysicsWorld::AddPhysicalObject(PhysicalObject* obj)
{
	m_World->addEntity(obj->GetBody());
}

void PhysicsWorld::Update(float deltaTime)
{
	m_World->stepDeltaTime(deltaTime);	
}